<?php

namespace app\base\controller\api;

use think\admin\Controller;
use app\base\model\AiApiConfig;
use app\base\controller\api\Auth;
use app\base\model\AiVoice;
use app\base\service\WsSendService;
use think\Exception;

/**
 * 各平台api参数配置
 * Class Login
 * @package app\store\controller
 */
class CrontabPush extends Controller
{
    public function execute()
    {
        // 获取所有启用的推送计划
        $schedules = $this->app->db->name("redian_push_schedule")->where('status', 1)->select();

        foreach ($schedules as $schedule) {
            if ($this->shouldPush($schedule)) {
                try {
                    $this->handlePush($schedule);
                } catch (\Exception $e) {
                   $this->app->log->error("推送失败_{$schedule['id']}：{$e->getMessage()}");
                }
            }
        }
    }

    // 判断是否需要推送
    private function shouldPush($schedule)
    {
        if ($schedule['schedule_type'] == 1) { // 每日时段
            $current = time();
            $schedule_values  = explode(',', $schedule['schedule_value']);
            $star_time = strtotime(date("Y-m-d").$schedule_values[0]);
            $end_time = strtotime(date("Y-m-d").$schedule_values[1]);
            if($current>$star_time && $current<$end_time){
                return true;
            }else{
                return false;
            }
        } else { // 间隔分钟
            return time() >= strtotime($schedule['next_push']);
        }
    }

    // 执行推送操作
    private function handlePush($schedule)
    {
        //判断设备是否在线
        $device = $this->app->db->name("ai_device")->where(['id'=>$schedule['target_device']])->value('status');

        if($device==0){
            $this->app->db->name("redian_push_log")->insert([
                'schedule_id' => $schedule['id'],
                'task_id' => $schedule['task_id'],
                'user_id' => $schedule['user_id'],
                'error_msg' => "设备不在线",
                'status'=>0
            ]);
            $this->app->log->error("推送失败_{$schedule['id']}：设备不在线");
            return false;
        }

        // 开启事务
        $this->app->db->startTrans();
        try {
            // 获取待推送数据（按创建时间排序）
            $dataIds = $this->app->db->name("redian_data")
                ->where([
                    'task_id'=>$schedule['task_id'],
                    'is_receive'=>0,
                    'video_status'=>3
                ])->where('push_num','<',6)->limit($schedule['push_num'])->column('id');

            if (empty($dataIds)) {
                // 提交事务
                $this->app->db->name("redian_push_schedule")->where(['id'=>$schedule['id']])->update(['status'=>2]);
                $this->app->db->commit();
                $this->app->log->error("推送失败_{$schedule['id']}：没有可推送的数据");
                throw new Exception('没有可推送的数据');
            }
            //获取对应平台执行脚本
            $script_file = $this->app->db->name("script_confg")
                ->whereIn('type', [0,$schedule['platform']])
                ->column('name');

            foreach ($dataIds as $dataId){
                $content = [
                        'type'=>1,
                        'script_file'=>$script_file,
                        'data_id'=>$dataId,
                        'is_update'=>1
                ];
                $this->app->log->info("推送_{$schedule['id']}：".json_encode($content));
                WsSendService::instance()->send($schedule['target_device'],1,$content);
                $this->app->db->name("redian_push_log")->insert([
                    'schedule_id' => $schedule['id'],
                    'task_id' => $schedule['task_id'],
                    'user_id' => $schedule['user_id'],
                    'status'=>1,
                    'data_id'=>$dataId
                ]);
            }


            // 更新下次推送时间
            if ($schedule['schedule_type'] == 2) {
                $next = strtotime("+{$schedule['schedule_value']} minutes");
                $this->app->db->name("redian_push_schedule")->where(['id'=>$schedule['id']])->update([
                    'last_push'=>date('Y-m-d H:i:s'),
                    'next_push' => date('Y-m-d H:i:s', $next)
                ]);
            }

            // 提交事务
            $this->app->db->commit();
        } catch (\Exception $e) {
            $this->app->db->rollback();
            $this->app->log->error("推送失败_{$schedule['id']}：{$e->getMessage()}");
            throw $e;
        }
    }

}
